<script setup>

import {onMounted, ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import qs from "qs";

const applicationArr=ref([])

const dialogVisible=ref(false)


//定义数组保存图片路径
const fileList = ref([])

const dialogImageUrl = ref('')

//定义变量用来保存图片提交的后端接口地址
const actionUrl = ref(BASE_URL+'/v1/file/upload');

const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
  //1.获取图片路径
  let imgUrl=uploadFile.response.data;
  if(imgUrl!=null && imgUrl!=''){
    //2.删除图片
    axios.post(BASE_URL+'/v1/file/remove?imgUrl='+imgUrl)
        .then(response=>{
          if(response.data.code==2000){
            ElMessage.success('删除成功')
          }
          else{
            ElMessage.error('删除失败')
          }
        })
  }
}

const tempImgUrl=ref('')
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
  console.log(fileList.value)
  tempImgUrl.value=fileList.value[0].response.data
}

const user=ref(getUser())
//定义数组用来保存新增申请单时的审批人（包含姓名）
const auditUserOpts=ref([])
//定义数组用来保存新增申请单时，对应审批人id，作入库使用
const auditUserIdList=ref([])
//定义加载审批人的方法
const loadAuditUser=()=>{
  let parentId=user.value.parentId
  if(parentId!=null){
    axios.get(BASE_URL+'/v1/user/select/audit?parentId='+parentId)
        .then(response=>{
          if (response.data.code==2000){
            auditUserOpts.value=response.data.data;
            for(let i =0;i<auditUserOpts.value.length;i++) {
              auditUserIdList.value.push(auditUserOpts.value[i].id)
            }
          }
          else{
            ElMessage.error(response.data.msg)
          }
        })
  }
}
const addApplicationDialogVisible=ref(false)

onMounted(()=>{
  //加载当前审批人（用车人）
  loadAuditUser();

  loadDictOptions(applicationStatus,"application_status")

  loadApplication()
})

const times=ref([])

const addForm=ref({
  departureAddr:'',//出发地
  destinationAddr:'',//目的地
  reason:'',//用车原因
  remark:''//备注
})

const handClose=()=>{
  times.value=[];
  fileList.value=[];
  addForm.value={};
  addApplicationDialogVisible.value=false
}

//定义新增申请单的方法
const addApplication=()=>{
  if(fileList.value.length==0){
    ElMessage.error('请上传驾照图片');
    return;
  }
  addForm.value.userId=user.value.id;
  addForm.value.username=user.value.username;
  addForm.value.startTime=times.value[0];
  addForm.value.endTime=times.value[1];
  addForm.value.imgUrl=fileList.value[0].response.data;
  addForm.value.auditUserIdList=auditUserIdList.value;
  console.log(addForm.value)

  let data=qs.stringify(addForm.value)
  axios.post(BASE_URL+'/v1/application/save',data)
      .then(response=>{
        if(response.data.code==2000){
          ElMessage.success("申请成功")
          times.value=[];
          fileList.value=[];
          addForm.value={};
          addApplicationDialogVisible.value=false
          loadApplication();
        }
        else{
          ElMessage.error(response.data.msg)
        }
      })
}

const applicationStatus=ref([])



const searchForm=ref({
  departureAddr:'',//出发地
  destinationAddr:'',//目的地
  status:''
})

const resetSearch=()=>{
  searchForm.value={}
  loadApplication();
}

const loadApplication=()=>{
  searchForm.value.userId=user.value.id;
  let data=qs.stringify(searchForm.value)
  axios.get(BASE_URL+'/v1/application/select?'+data)
      .then(response=>{
        if(response.data.code==2000){
          applicationArr.value=response.data.data
          console.log(applicationArr.value)
          // ElMessage.success("查询成功")
        }
        else{
          ElMessage.error(response.data.msg)
        }
      })
}

const formatStatus=(row,column,cellValue,index)=>{
  if(!applicationStatus.value){
    return cellValue;
  }
  for(let item of applicationStatus.value){
    if(item.value==cellValue){
      cellValue=item.label;
    }
  }
  return cellValue;
}

const cancel=(id)=>{
  let data=qs.stringify({id:id})
  axios.post(BASE_URL+'/v1/application/cancel',data)
      .then(response=>{
        if(response.data.code==2000){
          ElMessage.success("撤销成功")
          loadApplication();
        }
        else{
          ElMessage.error(response.data.msg)
        }
      })
}
</script>

<template>
<!--  <el-upload-->
<!--      v-model:file-list="fileList"-->
<!--      v-model:action="actionUrl"-->
<!--      name="file"-->
<!--      limit="1"-->
<!--      list-type="picture-card"-->
<!--      :on-preview="handlePictureCardPreview"-->
<!--      :on-remove="handleRemove"-->
<!--  >-->
<!--    <el-icon><Plus /></el-icon>-->
<!--  </el-upload>-->

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl"/>
  </el-dialog>

<!--  <hr>-->

<!--  <h4>显示后端放回的图片路径：{{tempImgUrl}}</h4>-->
<!--  <img :src="BASE_URL+tempImgUrl" alt="">-->

  <div style="padding:10px 20px;height: 6vh;background-color: #fff">
    <span style="line-height: 60px;font-size: 20px">申请单列表</span>
    <el-button type="primary" style="float: right;margin-top: 10px" @click="addApplicationDialogVisible=true" v-if="user.parentId!==null">申请用车</el-button>
  </div>
  <div style="height: 84vh;">
    <el-card style="margin:10px;height: 70px">
      <el-form label-width="82px" :inline="true">
        <el-form-item label="出发地" style="">
          <el-input placeholder="出发地" v-model="searchForm.departureAddr" @keydown.enter="loadApplication"></el-input>
        </el-form-item>
        <el-form-item label="目的地" >
          <el-input placeholder="目的地" v-model="searchForm.destinationAddr" @keydown.enter="loadApplication"></el-input>
        </el-form-item>
        <el-form-item label="申请单状态">
          <el-select placeholder="申请单状态" style="width: 200px;" v-model="searchForm.status" @change="loadApplication">
            <el-option v-for="item in applicationStatus" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="loadApplication">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin:10px;padding: 0 20px">
      <el-table :data="applicationArr" style="width: 100%">
        <el-table-column type="index" label="编号" align="center" width="80"></el-table-column>
        <el-table-column prop="username" label="申请人" align="center"></el-table-column>
        <el-table-column prop="departureAddr" label="出发地" align="center"></el-table-column>
        <el-table-column prop="destinationAddr" label="目的地" align="center"></el-table-column>
        <el-table-column prop="reason" label="用车原因" align="center"></el-table-column>
        <el-table-column prop="auditUsernameList" label="审批人" align="center">
        </el-table-column>
        <el-table-column prop="startTime" label="使用开始时间" align="center"></el-table-column>
        <el-table-column prop="endTime" label="使用结束时间" align="center"></el-table-column>
        <el-table-column :formatter="formatStatus" prop="status" label="申请单状态" align="center"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button link type="primary" @click="cancel(scope.row.id)" :disabled="scope.row.status!=10">撤销</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>


    <el-dialog title="创建申请单" v-model="addApplicationDialogVisible"style="width:1000px;padding:40px;" :before-close="handleClose">
      <el-form label-width="80px" label-position="top">
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="用车人">
              <el-input readonly v-model="user.username"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用时间">
              <el-date-picker
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  format="YYYY-MM-DD HH:mm:ss"
                  v-model="times"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="车辆出发地">
              <el-input placeholder="请输入" v-model="addForm.departureAddr"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车辆目的地">
              <el-input placeholder="请输入" v-model="addForm.destinationAddr"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="用车事由">
              <el-input placeholder="请输入" type="textarea" resize="none" :rows="3"  v-model="addForm.reason"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input placeholder="请输入" type="textarea" resize="none" :rows="3" v-model="addForm.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="驾照">
              <el-upload
                  v-model:file-list="fileList"
                  v-model:action="actionUrl"
                  name="file"
                  limit="1"
                  list-type="picture-card"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
              >
                <el-icon>
                  <Plus/>
                </el-icon>
              </el-upload>
              <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl"/>
              </el-dialog>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审批人">
              <el-row :gutter="10">
                <el-col :span="12" v-if="auditUserOpts.length>0">
                  <el-tag type="primary">
                    <el-icon style="margin-right:5px;position:relative;top:2px;">
                      <User/>
                    </el-icon>
                    <span>{{ auditUserOpts[0].username }}</span>
                  </el-tag>
                </el-col>
                <el-col :span="12" v-if="auditUserOpts.length>1">
                  <el-tag type="primary">
                    <el-icon style="margin-right:5px;position:relative;top:2px;">
                      <User/>
                    </el-icon>
                    <span>{{ auditUserOpts[1].username }}</span>
                  </el-tag>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="addApplication">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>

</style>